package com.xxgc.wujiaoservice.util;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.audio.SingleFileAudioPlayer;
import org.springframework.stereotype.Component;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

/**
 * 中文语音合成工具类，支持中文语音合成和播放
 */
@Component
public class TextToSpeechUtil {

    // 中文语音引擎
    private static final String CHINESE_VOICE = "cmu-slt-hsmm";
    // 英文语音引擎
    private static final String ENGLISH_VOICE = "kevin16";

    // 中文词典路径配置
    private static final String CMULEX_DIR = "/path/to/cmulex";

    static {
        // 配置FreeTTS语音引擎
        System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory");
        System.setProperty("freetts.vocab.zh_cn.cmulex.dir", CMULEX_DIR);
    }

    /**
     * 将文本合成为语音并播放
     * @param text 待合成的文本
     * @param isChinese 是否为中文
     */
    public void speak(String text, boolean isChinese) {
        Voice voice = getVoice(isChinese);
        try {
            voice.allocate();
            voice.speak(text);
        } catch (Exception e) {
            throw new RuntimeException("语音合成失败", e);
        } finally {
            if (voice != null) {
                voice.deallocate();
            }
        }
    }

    /**
     * 将文本合成为语音并保存为WAV文件
     * @param text 待合成的文本
     * @param filePath 保存路径
     * @param isChinese 是否为中文
     */
    public void speakToFile(String text, String filePath, boolean isChinese) {
        Voice voice = getVoice(isChinese);
        try {
            voice.allocate();
            // 设置音频输出文件
            SingleFileAudioPlayer audioPlayer = new SingleFileAudioPlayer(filePath, AudioFileFormat.Type.WAVE);
            voice.setAudioPlayer(audioPlayer);
            voice.speak(text);
            // 关闭音频播放器并保存文件
            voice.getAudioPlayer().close();
        } catch (Exception e) {
            throw new RuntimeException("语音合成到文件失败", e);
        } finally {
            if (voice != null) {
                voice.deallocate();
            }
        }
    }

    /**
     * 播放已有的语音文件
     * @param filePath 文件路径
     */
    public void playAudioFile(String filePath) {
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(filePath))) {
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();

            // 等待播放完成
            Thread.sleep(clip.getMicrosecondLength() / 1000);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException | InterruptedException e) {
            throw new RuntimeException("播放音频文件失败", e);
        }
    }

    /**
     * 获取语音引擎实例
     * @param isChinese 是否为中文
     * @return 语音引擎实例
     */
    private Voice getVoice(boolean isChinese) {
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice voice;

        if (isChinese) {
            voice = voiceManager.getVoice(CHINESE_VOICE);
            if (voice == null) {
                throw new RuntimeException("无法加载中文语音引擎，请确保中文语音包正确配置");
            }
        } else {
            voice = voiceManager.getVoice(ENGLISH_VOICE);
            if (voice == null) {
                throw new RuntimeException("无法加载英文语音引擎");
            }
        }

        return voice;
    }

    public static void main(String[] args) {
        TextToSpeechUtil util = new TextToSpeechUtil();
        // 测试中文语音
        //util.speak("你好，这是中文语音测试", true);
        // 测试英文语音
        util.speak("Hello, this is an English voice test", false);
    }
}